import axios from 'axios';

// API基础URL
// const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
const API_BASE_URL = 'https://python.knomi.me';
// const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://127.0.0.1:8000';

// 获取访客token
const getVisitorToken = () => {
  return localStorage.getItem('visitor_token') || '';
};

// 聊天相关接口
interface SendMessageParams {
  sessionId?: string;
  messages: Array<{
    role: 'user' | 'assistant';
    content: string;
  }>;
  stream?: boolean;
  generate_voice?: boolean;
  chatId?: string;
}

interface SendMessageResponse {
  response: string;
  emotion_analysis?: Record<string, number>;
  session_id: string;
  history: Array<{
    role: 'user' | 'assistant';
    content: string;
  }>;
}

interface StreamChunkResponse {
  chunk?: string;
  text?: string;
  done: boolean;
  emotion_analysis?: Record<string, number>;
  session_id?: string;
  history?: Array<{
    role: 'user' | 'assistant';
    content: string;
  }>;
}

interface ChatMessage {
  id: string;
  content: string;
  sender: 'user' | 'ai';
  timestamp: Date;
  emotionAnalysis?: any;
}

// 聊天API客户端
const chatAPI = {
  // 发送消息（支持流式响应）
  sendMessage: async (
    params: SendMessageParams,
    onChunk?: (chunk: string) => void
  ): Promise<SendMessageResponse> => {
    try {
      if (params.stream && onChunk) {
        const response = await fetch(`${API_BASE_URL}/chat/`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${getVisitorToken()}`
          },
          body: JSON.stringify({
            messages: [{
              role: 'user',
              content: params.messages[0].content
            }],
            session_id: params.sessionId,
            stream: true,
            generate_voice: false,
            chat_id: params.chatId
          })
        });

        const reader = response.body?.getReader();
        const decoder = new TextDecoder();
        let fullResponse = '';
        let finalResponse: SendMessageResponse | null = null;

        if (!reader) {
          throw new Error('Failed to get response reader');
        }

        // Make sure we have a timeout in case the loop gets stuck
        let timeoutId = setTimeout(() => {
          console.error('Stream reading timeout after 60s');
          reader.cancel();
        }, 60000);

        try {
          while (true) {
            const { value, done } = await reader.read();
            if (done) break;

            const chunk = decoder.decode(value);
            const lines = chunk.split('\n');

            for (const line of lines) {
              if (line.trim() === '') continue;

              if (line.startsWith('data: ')) {
                try {
                  const data: StreamChunkResponse = JSON.parse(line.slice(6));
                  if (!data.done) {
                    // Use data.text instead of data.chunk since the API returns text property
                    const textContent = data.text || data.chunk || '';
                    fullResponse += textContent;
                    onChunk(textContent);
                    console.log('接收数据块:', data);
                  } else if (data.done) {
                    // Handle the case when the done message comes
                    console.log('流式响应完成:', data);

                    // data.emotion_analysis &&
                    if (data.session_id) {
                      finalResponse = {
                        response: fullResponse,
                        emotion_analysis: data.emotion_analysis,
                        session_id: data.session_id,
                        history: data.history || []
                      };
                      console.log('最终响应数据:', finalResponse);
                    } else {
                      // If done=true but no emotion_analysis yet, save what we have for now
                      // The API might send another message with emotion data
                      finalResponse = {
                        response: fullResponse,
                        emotion_analysis: {},
                        session_id: data.session_id || params.sessionId || '',
                        history: data.history || []
                      };
                    }

                    // If we got a done message, we can break out of the loop
                    if (data.done) {
                      reader.cancel();
                      break;
                    }
                  }
                } catch (e) {
                  console.error('Failed to parse chunk:', e, line);
                }
              }
            }
          }
        } catch (err) {
          console.error('cuow', err)
        }
        finally {
          // Make sure we clear the timeout
          clearTimeout(timeoutId);
        }

        // If no final response was constructed by the loop, create a default one
        if (!finalResponse) {
          finalResponse = {
            response: fullResponse,
            emotion_analysis: {},
            session_id: params.sessionId || '',
            history: []
          };
          console.log('创建默认响应:', finalResponse);
        }

        return finalResponse;
      } else {
        const response = await axios.post(`${API_BASE_URL}/chat/`, {
          messages: [{
            role: 'user',
            content: params.messages[0].content
          }],
          session_id: params.sessionId,
          stream: false
        }, {
          headers: {
            'Authorization': `Bearer ${getVisitorToken()}`
          }
        });

        return {
          response: response.data.response,
          emotion_analysis: response.data.emotion_analysis,
          session_id: response.data.session_id,
          history: response.data.history
        };
      }
    }
    catch (error) {
      console.error('发送消息失败1:', error);
      throw error;
    }
  },

  // 获取聊天历史
  getChatHistory: async (sessionId: string): Promise<ChatMessage[]> => {
    try {
      const response = await axios.get(`${API_BASE_URL}/chat/${sessionId}/history`, {
        headers: {
          'Authorization': `Bearer ${getVisitorToken()}`
        }
      });
      return response.data.history.map((msg: any, index: number) => ({
        id: `history_${Date.now()}_${index}`,
        content: msg.content,
        sender: msg.role === 'user' ? 'user' : 'ai',
        timestamp: new Date(),
        emotionAnalysis: msg.emotion_analysis
      }));
    } catch (error) {
      console.error('获取聊天历史失败:', error);
      return [];
    }
  },

  // 创建聊天会话
  createSession: async (): Promise<string> => {
    try {
      const response = await axios.post(`${API_BASE_URL}/chat/`, {
        messages: [{
          role: 'user',
          content: 'hello'
        }]
      }, {
        headers: {
          'Authorization': `Bearer ${getVisitorToken()}`
        }
      });
      return response.data.session_id;
    } catch (error) {
      console.error('创建聊天会话失败:', error);
      throw error;
    }
  }
};

export default chatAPI; 